package com.example.sys.async.handler.impl;

import com.example.sys.async.po.SysASync;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;

/***
 * Rabbitmq异步处理器实现类
 */
public class RabbitmqHandlerImpl extends AbstractASyncHandlerImpl {

    Logger logger = LoggerFactory.getLogger(getClass());

    private AmqpTemplate amqpTemplate;

    public AmqpTemplate getAmqpTemplate() {
        if (this.amqpTemplate == null) {
            this.amqpTemplate = getApplicationContext().getBean(AmqpTemplate.class);
        }
        return this.amqpTemplate;
    }


    /***
     * 推送MQ消息
     * @param sysASync
     * @return
     */
    @Override
    public SysASync handler(SysASync sysASync) {
        try {
            sysASync.setSuccessed(true);
            getAmqpTemplate().convertAndSend(sysASync.getTarget(), sysASync.getContext());
            logger.info("MQ推送成功：{}", sysASync);
        } catch (Exception e) {
            sysASync.setSuccessed(false);
            sysASync.setError(e.getMessage());
            logger.warn("MQ推送失败：", sysASync.getContext());
        }
        return sysASync;
    }
}
